package com.wxy.demo.controller;

import com.wxy.demo.dao.UserRepository;
import com.wxy.demo.dto.LoginTokenDto;
import com.wxy.demo.dto.UserLoginDto;
import com.wxy.demo.entity.User;
import com.wxy.demo.util.ApiResponse;
import com.wxy.demo.util.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/***
 * <p>
 * Description: 登录接口
 * </p>
 * @author wangxiaoyuan
 * 2021年12月10日
 */
@RestController
public class LoginController {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private TokenUtils tokenUtils;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 刷新令牌
     *
     * @return
     */
    @PostMapping("/refreshToken")
    public Object refreshToken(HttpServletRequest request) {
        //从请求头中获取refreshToken
        String oldRefreshToken = request.getHeader("refreshToken");
        //校验refreshToken，如果令牌没有过期
        if (tokenUtils.isTokenExpired(oldRefreshToken)) {
            return ApiResponse.fail("刷新令牌已过期，请重新登录！");
        }
        //解析refreshToken
        String username = tokenUtils.getUsernameFromToken(oldRefreshToken);
        //生成新的accessToken
        String newAccessToken = tokenUtils.createToken(username);
        String newRefreshToken = tokenUtils.refreshToken(newAccessToken);
        LoginTokenDto loginTokenDto = LoginTokenDto.builder().accessToken(newAccessToken).refreshToken(newRefreshToken).build();
        return ApiResponse.ok("令牌请求成功！", loginTokenDto);
    }

    @PostMapping("/login")
    public Object login(@RequestBody UserLoginDto dto) {
        // 判断登录逻辑
        User user = userRepository.findByUsername(dto.getUsername());
        if (user == null) {
            return ApiResponse.fail("当前用户不存在");
        }
        if (!passwordEncoder.matches(dto.getPassword(), user.getPassword())) {
            return ApiResponse.fail("用户名或密码错误");
        }
        // 生成token
        String accessToken = tokenUtils.createToken(dto.getUsername());
        String refreshToken = tokenUtils.refreshToken(accessToken);
        LoginTokenDto loginTokenDto = LoginTokenDto.builder().accessToken(accessToken).refreshToken(refreshToken).build();
        return ApiResponse.ok(loginTokenDto);
    }
}
